#ifndef _WECHAT_H_
#define _WECHAT_H_

#include "rand-isaac.h"

//#define DEBUG

#ifdef DEBUG
#define fgets_common fgets
#else
#define fgets_common fgets_pipe
#endif 

//video decriptio
//128KB of video HEAD is cryptographic with ISACC
#define WXISAAC_LEN 131072

#define LINE_MAX_LEN 4096

enum video_state {
	VIDEO_URL_READY = 0, //got url, not download
	VIDEO_DOWNLOADING, //downloading
	VIDEO_DOWNLAODED, //downloaded
};

enum app_state {
	APP_STATE_UNINIT = 0,
	APP_STATE_INITED,
	APP_STATE_RUN,
	APP_STATE_DOWNLOADING,
	APP_STATE_EXITING,
	APP_STATE_EXIT
};

struct video_info {
	char url[4096];
	char title[1024]; //GB2312
	int duration; //seconds
	size_t size; //bytes
	uint64_t seed;

	enum video_state state;
};

#define MAX_SHOW_TITLE_LEN 32 //32 bytes
#define MAX_VIDEO_NUM 32
extern int current_video_index; //read thread for mitmdump, update this index
extern struct video_info video_info[MAX_VIDEO_NUM];

extern enum app_state gstate;
/*
* ISAAC64
* product 131072 random number by seed
*
* in: seed
* out: keys[131072]
*/
extern void get_decryptor_array(uint64_t seed, uint8_t* keys);

/*
* in: keys[131072]
* in: video with ISAAC encryption
* out: video with decryption
*/
extern int decode_video(uint8_t* keys, char* video_in, char* video_out);

/*
* in: seed
* in: video with ISAAC encryption
* out: video with decryption
*/
extern int decode_video_with_seed(uint64_t seed, char* video_in, char* video_out);

//mitm
extern void mitm_init(void);

//start mitm service
extern int mitm_start(void);

//capture https packets
extern int wechat_catpture(void);

extern void mitm_exit(void);

/*
* parse video info
* 
* in: mitm output
* out: video info pointer
* 
* return 1 if got video
* return 0 otherwise
*/
extern int parse_http_packet(FILE* fp, struct video_info* pvideo);

enum log_mark {
	MARK_INIT = 0,

	MARK_SB_INFO, //[09:00:25.988] HTTP(S) proxy listening at *:8080.
	MARK_SB2_INFO, //[09:00:42.971][127.0.0.1:15892] client connect
	MARK_SB_UNEXPECT, //[09:00 : 50.961][127.0.0.1:15948] Unexpected data from server :

	MARK_LIP_GET, //127.0.0.1:15892: GET https://wx.qlogo.cn
	MARK_LIP_POST, //127.0.0.1:15929: POST https://channels.weixin.qq.com/web/report-perf
	MARK_LIP_HEAD, //127.0.0.1:15948: HEAD
	MARK_LIP_OPTIONS, //127.0.0.1:15940: OPTIONS https://www.httpbin.org/post HTTP/2.0
	MARK_JSON //"json": {
};

enum next_mark {
	NEXT_MARK_ALL, //any MARK 
	NEXT_MAKR_LINEEND, //MARK_SB_UNEXPECT
};

extern enum log_mark parse_one_line(char* line);

#endif
